<?php
include_once("CSS.class.php");
include_once("JS.class.php");
include_once("EventManager.class.php");
include_once("FormFactory.class.php");

class Form
{
	var $rows = array();
	var $css;
	var $js;
	var $jsPath;
	var $events;
	var $template;
	var $factory;
	var $__maxCols = 0;
	var $isValid = true;
	var $errors = array();
	var $input_class = "";

	function Form()
	{
		$this->css = new CSS;
		$this->js  = new JS($this);
		$this->events  = new EventManager;
		$this->template['form']   = "<table{params}>\n<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\"{enctype}>\n<input type=\"hidden\" name=\"postBack\" value=\"sended\" />\n\t{rows}</form></table>";
		$this->template['errors'] = "<div class=\"errors\">Se han producido los siguientes errores:<br />{errors}</div>";
		$this->template['error']  = "<div class=\"error\">- {error}</div>";
	}

	function createFactory()
	{
		$this->factory = new FormFactory;
		$this->factory->setForm($this);
	}
	function display()
	{
		$rows = "";
		$enctype = "";
		$first = null;
		if (count($this->rows) > 0)
		{
			foreach($this->rows as $i => $row)
			{
				if ($i == 0)
				{
					$first = $row;
				}
				if ($row->cantCols > $this->__maxCols)
				{
					$this->__maxCols = $row->cantCols;
				}
				if ($row->hasFile)
				{
					$enctype = " enctype=\"multipart/form-data\"";
				}
			}

			foreach($this->rows as $i => $row)
			{
				$row->__maxCols = $this->__maxCols;
				$rows .= $row->getHTML();
			}
			if (!empty($first) && method_exists($first, "getFirstID"))
			{
			$js     = "
			<script type=\"text/javascript\" src=\"".$this->jsPath."prototype.js\"></script>
			<script type=\"text/javascript\">
				$('".$first->getFirstID()."').focus();
			</script>";
			}
		}

		$params = $this->css->getCSS() . $this->events->getEvents();

		$form   = str_replace(array('{params}', '{rows}', '{enctype}'), array($params, $rows, $enctype), $this->template['form']);
		if (count($this->errors) > 0)
		{
			$errors = str_replace("{errors}", $this->__getErrors(), $this->template['errors']);
		}

		echo $errors . $form . $js;
	}

	function __getErrors()
	{
		$ret = "";
		foreach($this->errors as $error)
		{
			$ret .= str_replace("{error}", $error, $this->template['error']);
		}
		return $ret;
	}

	function isValid()
	{
		return $this->isValid;
	}

	function add($object)
	{
		if (get_class($object) != 'row')
		{
			$row = $this->factory->newRow();
			$row->add($object);

			if ($this->isValid)
			{
				$this->isValid = $this->isValid && $object->isValid();
			}
			$this->add($row);
		} else {
			$this->rows[] = $object;

			if ($this->isValid)
			{
				$this->isValid = $this->isValid && $object->isValid();
			}
		}
	}

	function addError($error)
	{
		$this->errors[] = $error;
	}
}

?>